package cn.gson.crm.controller.money;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.CuiKuanDao;
import cn.gson.crm.model.dao.EmpDao;
import cn.gson.crm.model.dao.ImagesDao;
import cn.gson.crm.model.dao.PayrecordDao;
import cn.gson.crm.model.dao.PayrecordDetailDao;
import cn.gson.crm.model.entity.Cuikuan;
import cn.gson.crm.model.entity.Emp;
import cn.gson.crm.model.entity.Images;
import cn.gson.crm.model.entity.Payrecord;
import cn.gson.crm.model.entity.PayrecordDetail;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.mapper.PayrecordMapper;
import lombok.extern.log4j.Log4j;

@Controller
@RequestMapping("/payrecord")
@Log4j
public class PayRecordController {
	
	@Autowired
	private PayrecordMapper payRecordMapper;

	/**
	 * 收款表
	 */
	@Autowired
	private PayrecordDao payrecordDao;
	
	/**
	 * 收款详情表
	 */
	@Autowired
	private PayrecordDetailDao payrecordDetailDao;
	
	/**
	 * 催款表
	 */
	@Autowired
	private CuiKuanDao cuikuanDao;
	
	/**
	 * 员工
	 */
	@Autowired
	private EmpDao empDao;
	
	/**
	 * 图片表
	 */
	@Autowired
	private ImagesDao imgDao ;
	
	/**
	 * 查询所有的收款记录
	 * @param payrecord
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String,Object> index(Payrecord payrecord, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		
		
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Payrecord> pageData = payRecordMapper.findAllPayrecord(payrecord);
		for(int i=0;i<pageData.size();i++) {
			Double money=(Double) payRecordMapper.sumMoney(pageData.get(i).getId());
			pageData.get(i).setShiJiao(money);
		}
		
		PageInfo<Payrecord> info = new PageInfo<>(pageData);
	
		
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 左边的集合
	 * @param payrecord
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("lists")
	@ResponseBody
	public Map<String,Object> indexs(Payrecord payrecord, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Payrecord> pageData = payRecordMapper.findAllPayrecords(payrecord);
		 
		PageInfo<Payrecord> info = new PageInfo<>(pageData);
		
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 查询所有大学生的收款记录
	 * @param payrecord
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("listss")
	@ResponseBody
	public Map<String,Object> indexss(Payrecord payrecord, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Payrecord> pageData = payRecordMapper.findAllPayrecordss(payrecord);
		 
		PageInfo<Payrecord> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Payrecord p;
		if (id != null && (p = payrecordDao.findOne(id)) != null) {
			p.setDeleted(false);
			obj.put("success", true);
		} else {
			obj.put("message", "收款记录不存在！");
		}
		return obj;
	}
	
	/**
	 * 编辑表单
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "add_payrecord", "add_payrecord/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			Payrecord p = payRecordMapper.findPayreordById(id);
			if (p != null) {		
				model.addAttribute("payrecord", p);
			}
		}	
		List<Map<String,Object>> stu=payRecordMapper.selectAllStudentName();
		model.addAttribute("stu",stu);
		model.addAttribute("stuof", stu.size());
		
		List<Map<String,Object>> className=payRecordMapper.selectAllClassName();
		model.addAttribute("className",className);
		
		List<Map<String,Object>> empName=payRecordMapper.selectAllEmpName();
		model.addAttribute("emp",empName);
		
		return "payrecord/add_payrecord";
	}

	/**
	 * 保存
	 * @param stuinfor
	 * @param br
	 * @return
	 */
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(@Valid Payrecord payrecord, BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		//设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		obj.put("success", false);
		Payrecord pay = new Payrecord();
		if(payrecord.getId()!=null) {
			 pay = payrecordDao.findOne(payrecord.getId());
		}
		//编辑
		if(payrecord.getId()!=null) {
			pay.setIdentity(payrecord.getIdentity());
			pay.setClasses(payrecord.getClasses());
			pay.setAllMoney(payrecord.getAllMoney());
			pay.setFinish(payrecord.getFinish());
			pay.setDiscountMoney(payrecord.getDiscountMoney());
			pay.setDiscountReason(payrecord.getDiscountReason());
			pay.setYingJiao(payrecord.getShiJiao());
			pay.setShiJiao(payrecord.getShiJiao());
			pay.setQianJiao(payrecord.getQianJiao());
			payrecordDao.save(pay);
			obj.put("success", true);
		}else {
			if (br.hasErrors()) {
				obj.put("message", "校验失败！");
				obj.put("erros", br.getFieldErrors());
			} else {
				if (payrecord.getStudent().getId() == null) {
						obj.put("message", "该用户不存在！");
				} else {
					if(payrecord.getDiscountMoney()==null) {
						payrecord.setYingJiao(payrecord.getAllMoney());
					} else {
						if((payrecord.getDiscountMoney()>=(payrecord.getAllMoney()))){
							obj.put("message", "优惠金额不能大于总金额！");
							return obj;
						} else {
							payrecord.setYingJiao(payrecord.getAllMoney()-payrecord.getDiscountMoney());
						}					
					}
					
					if(payrecord.getShiJiao()==null) {
						payrecord.setQianJiao(payrecord.getYingJiao());
					}else {
						payrecord.setQianJiao(payrecord.getYingJiao()-payrecord.getShiJiao());
					}
					// new Date()为获取当前系统时间
					String today = df.format(new Date());
					obj.put("success", true);
					payrecord.getStudent().setState("待分班");
					payrecord.setDate(today);
					payrecord.setDeleted(true);
					payrecordDao.save(payrecord);
					
				}	
			}
		}
		return obj;
	}
	
	/**
	 * 查询所有的收款记录
	 * @param payrecord
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping("payrecord_detail/{id}/{name}")
	public String indexs(@PathVariable(name = "id", required = false) Long id,
			@PathVariable(name = "name", required = false) String name,Payrecord pr,Model model){
		
		Payrecord payrecord =payrecordDao.findOne(id);
		model.addAttribute("AllMoney", payrecord.getAllMoney());
		model.addAttribute("payrecord", payrecord);
		model.addAttribute("detailId",id);
		model.addAttribute("name",name);
		return "payrecord/payrecord_detail";
	
	}
	

	/**
	 * 查询所有的收款记录
	 * @param payrecord
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/allDetail/{id}")
	@ResponseBody
	public Map<String,Object> indexs(@PathVariable(name = "id", required = false) Long detailId,PayrecordDetail pd, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<PayrecordDetail> pageData = payRecordMapper.findAllPayrecordDetail(detailId);
		PageInfo<PayrecordDetail> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
		
	/**
	 * 删除收款详情
	 * @param id
	 * @return
	 */
	@GetMapping("deleteDetail/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> deleteDetail(@PathVariable("id") Long id) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		PayrecordDetail pd ;
		if (id != null && ((pd = payrecordDetailDao.findOne(id)) != null)) {
			pd.setDeleted(false);
			obj.put("success", true);
		} else {
			obj.put("message", "收款详情不存在！");
		}
		return obj;
	}
	
	
	/**
	 * 收款详情的编辑表单
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "add_payrecord_detail/{ids}", "add_payrecord_detail/{id}/{ids}" })
	public String detailForm(@PathVariable(name = "ids", required = false) Long ids,@PathVariable(name = "id", required = false) Long id, Model model) {
		System.err.println("id"+id);
		if (id != null) {
			
			PayrecordDetail detail = payRecordMapper.findPayreordDetailById(id);
			if (detail != null) {		
				model.addAttribute("detail", detail);			
			}
		}
		List<Map<String,Object>> stu=payRecordMapper.selectAllStudentName();
		model.addAttribute("stu",stu);
		
		List<Map<String,Object>> empName=payRecordMapper.selectAllEmpName();
		model.addAttribute("emp",empName);
		
		Payrecord pay=payrecordDao.findOne(ids);
		model.addAttribute("pay", pay);
		return "payrecord/add_payrecord_detail";
	}

	
	@Value("${upload.file}")
	private String uploadDir;
	/**
	 * 收款详情的保存
	 * @param stuinfor
	 * @param br
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	Double sj=0d;
	@PostMapping("detail_save")
	@ResponseBody
	@Transactional
	public Map<String,Object> detailSave(
			@Valid PayrecordDetail detail,
			BindingResult br,
			@RequestParam(defaultValue="public") String type,
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request) throws IllegalStateException, IOException {	
		Map<String,Object> obj = new HashMap<String, Object>();
		//获取学生的应交金额
		Double yingJiao=detail.getPayrecord().getYingJiao();
		//将每一次的缴费累加
		sj=detail.getMoney()+sj;

		
			//设置路径
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			String dateDir = sdf.format(new Date());
			//获取文件后缀名
			String ext = FilenameUtils.getExtension(file.getOriginalFilename());
			String newFileName = UUID.randomUUID().toString()+"."+ext;
			String filePath = String .format("%s/%s/%s", uploadDir,type,dateDir);
			File fileDir = new File(filePath);
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
			Images img = new Images();
			img.setDelete(true);
			img.setImageType(file.getContentType());
			img.setModeType(type);
			img.setName(file.getOriginalFilename());
			img.setPath(String.format("%s/%s/%s", type,dateDir,newFileName));
			img.setSize(file.getSize());
			img.setSuffix(ext);
			img.setUploaddate(new Date());
			//将图片路径保存到数据库
			imgDao.save(img);
			file.transferTo(new File(fileDir, newFileName));
			obj.put("success", false);
			
		
			if (br.hasErrors()) {
				obj.put("message", "校验失败！");
				obj.put("erros", br.getFieldErrors());
			} else {
				Double sj=detail.getMoney()+detail.getMoney();
				detail.getPayrecord().setShiJiao(sj);
				detail.setImage(img);
				detail.setDeleted(true);	
				payrecordDetailDao.save(detail);
				obj.put("success", true);
				
			}
	
		
	return obj;
	}
	
	
	/**
	 * 催款信息的添加
	 */
	@PostMapping("cuikuan_save/{ids}")
	@ResponseBody
	@Transactional
	public Map<String,Object> cuiSave(@PathVariable(name = "ids", required = false) Long[] ids,HttpSession session ,Model model) {
		Map<String,Object> obj = new HashMap<String, Object>();
		//获取员工
		Emp emp=((User)session.getAttribute("user")).getEmp();
		//获取班主任
		Emp teacher=empDao.findOne(ids[1]);
		//获取收款记录
		Payrecord record=payrecordDao.findOne(ids[0]);
		Cuikuan s=new Cuikuan();
		s.setStatu("进行中");
		s.setEmp(emp);
		s.setEmpTeacher(teacher);
		s.setPayrecord(record);
		cuikuanDao.save(s);
		return obj;
	}
	
	
	/**
	 * 编辑表单
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("my_massage")
	public String open() {
		return "payrecord/my_massage";
	}
	
	/**
	 * 催款信息的查询
	 */
	@RequestMapping("messagelist")
	@ResponseBody
	public Map<String,Object> list(Cuikuan cuikuan, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,HttpSession session){
		
		//获取当前登录的员工id
		Long empTeacher=((User)session.getAttribute("user")).getEmp().getId();
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Cuikuan> pageData = payRecordMapper.findAllCuiKuan(empTeacher);
		PageInfo<Cuikuan> info = new PageInfo<>(pageData);
		
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 关闭
	 */
	@PostMapping("close")
	@ResponseBody
	@Transactional
	public Map<String,Object> close(@Valid Cuikuan cuikuan, BindingResult br,HttpSession session) {
		Map<String,Object> obj = new HashMap<String, Object>();
		Long empTeacher=((User)session.getAttribute("user")).getEmp().getId();
		List<Cuikuan> pageData = payRecordMapper.findAllCuiKuan(empTeacher);
		for(int i=0;i<pageData.size();i++) {
			pageData.get(i).setStatu("已处理");
			cuikuanDao.save(pageData.get(i));
			
		}	
		return obj;
		
	}
	
	/**
	 * 预览
	 */
	@GetMapping("ylimg/**")
	@ResponseBody
	public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletPath();
		path = path.replaceFirst("payrecord/ylimg/", uploadDir);
		log.info(path);
		ServletOutputStream os = response.getOutputStream();
		File f = new File(path);
		log.info(f);
		if (!f.exists()) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}
		// 创建一个输入流
		FileInputStream fis = new FileInputStream(f);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}
	
}
